#include "loginbrowser.h"
#include "../logic/user.h"

#include <QtDebug>
#include <QLayout>

LoginBrowser::LoginBrowser( QWidget * parent ) : QWebView( parent ), maxAuthProgress( 0 ) {
    // LoginBrowser signals are provided by handling QWebView signals
    connect( this, SIGNAL( loadProgress( int ) ), this, SLOT( handleProgress( int ) ) ); 
    connect( this, SIGNAL( loadFinished( bool ) ), this, SLOT( handleLoadFinished() ) );
    connect( this, SIGNAL( urlChanged( QUrl ) ), this, SLOT( handleUrlChanged( QUrl ) ) );

    this->setContentsMargins( 0, 0, 0, 0 );
    /*
    this->layout()->setSpacing( 0 );
    this->layout()->setMargin( 0 );
    */
}

void LoginBrowser::handleProgress( int progress ) {
    if ( this->url().toString() == "https://twitter.com/oauth/authorize" && !this->url().hasQuery() ) {
        if ( this->maxAuthProgress > progress ) { // got progress smaller than expected!
            qDebug() << "progress!" << progress << this->maxAuthProgress;
            return;
        }
        this->maxAuthProgress = progress;
        emit this->authenticationProgress( progress );

        return;
    }
}

void LoginBrowser::handleUrlChanged( QUrl url ) {
    if ( url.path() == "/oauth/authorize" && url.hasQuery() ) {
        emit this->loginLoadStarted();

        return;
    }
    else if ( url.path() == "/oauth/authorize" ) {
        emit this->authenticationStarted();

        return;
    }
    else if ( this->url().toString() == "http://socialwhale.com/oauth?return=" ) {
        User::instance()->loadFromBrowser( this );
        emit this->authenticationFinished();

        return;
    }
}

void LoginBrowser::handleLoadFinished() {
    if ( this->url().path() == "/oauth/authorize" && this->url().hasQuery() ) {
        emit this->loginLoadFinished();

        return;
    }
}

// load login page
void LoginBrowser::loadLogin() {
    this->load( QUrl( "http://socialwhale.com/login?oauth=start&return=http%3A%2F%2Fsocialwhale.com%2Foauth%3Freturn%3D" ) );
}
